var app = getApp();

const fetch = require('../../utils/fetch');
/**
 * 左滑
 */
function isLeftSlide(e) {
  const {
    startX,
    startY
  } = this.data.gesture;
  if (this.slideLock) {
    const t = e.touches[0];
    const deltaX = t.clientX - startX;
    const deltaY = t.clientY - startY;
    if (deltaX < -20 && deltaX > -40 && deltaY < 8 && deltaY > -8) {
      this.slideLock = false;
      return true;
    } else {
      return false;
    }
  }
}
/**
 * 右滑
 */
function isRightSlide(e) {
  const {
    startX,
    startY
  } = this.data.gesture;
  if (this.slideLock) {
    const t = e.touches[0];
    const deltaX = t.clientX - startX;
    const deltaY = t.clientY - startY;

    if (deltaX > 20 && deltaX < 40 && deltaY < 8 && deltaY > -8) {
      this.slideLock = false;
      return true;
    } else {
      return false;
    }
  }
}
const conf = {
  data: {
    hasEmptyGrid: false,
    showView: true,
    hidden: true
  },
  getTodayMsg(e) {
    const timeArr = this.data.timeArr; // 所有例假开始的时间
    const get_day = e.currentTarget.dataset.idx + 1;
    const recordid = e.currentTarget.dataset.recordid;
    // 点击的日期
    let cycle_day = this.data.cur_year + '-' + this.data.cur_month + '-' + get_day;
    // 点击日期的时间戳
    let cycle_dayTime = new Date(this.formatDate(cycle_day));
    // 需要知道当前日期, 在哪个例假范围内
    let index = timeArr.findIndex((v, i) => {
      // time 表示每个日期的时间戳
      var time = new Date(this.formatDate(v));
      if (time > cycle_dayTime) {
        return true;
      }
    });
    // 处理 index
    if (index === -1) {
      index = timeArr.length - 1;
    } else {
      index--;
    }
    // 当前点击日期所在的例假第一天的时间戳
    let cycle_first = new Date(this.formatDate(timeArr[index])).getTime();
    let cycle_days = (cycle_dayTime - cycle_first) / 1000 / 3600 / 24 + 1;
    this.setData({
      cur_date: get_day,
      cycle_day,
      cycle_days
    })
    let detectionData = this.data.detectionData
    this.details(get_day, detectionData)
    if (recordid) {
      this.setData({
        recordid
      });
      wx.showLoading({
        title: '加载中',
      })
      this.dailyRecords(recordid)
    } else {
      this.setData({
        recordid: null
      })
    }
  },
  details: function (get_day, detectionData) { //备孕详情
    var test_data = detectionData.filter(function (v, index) {
      let day_num = v[0].detectionTime.split(" ")[0].split("-")[2]
      let day;
      if (day_num < 10) {
        day = v[0].detectionTime.split(" ")[0].split("-")[2].substr(1, 1)
      } else {
        day = v[0].detectionTime.split(" ")[0].split("-")[2]
      }
      if (day == get_day) {
        for (var i = 0; i < v.length; i++) {
          v[i].time = v[i].detectionTime.split(" ")[1].split(":").splice(0, 2).join(":")
        }
        return v
      }
    })
    this.setData({
      test_data
    })
  },
  formatDate: function (time) {
    //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式   
    return time.replace(/\-/g, "/");
  },
  getSystemInfo() {
    const res = wx.getSystemInfoSync();
    this.setData({
      viewWidth: res.windowWidth / 7
    });
  },
  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate(); //返回一个月总天数 

  },
  getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay(); //返回1号是星期几
  },
  calculateEmptyGrids(year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month); //返回1号是星期几
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i); //前面加空天数
      }
      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
  },
  calculateDays(year, month) {
    let days = [];
    const thisMonthDays = this.getThisMonthDays(year, month); //返回一个月总天数 
    for (let i = 1; i <= thisMonthDays; i++) {
      days.push({
        day: i
      });
    }
    var dateItem = {
      id: year + '-' + month,
      year: year,
      month: month,
      days: days
    }
    this.setData({
      dayList: dateItem
    });
  },
  toDoday() { //回到今天
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const cur_date = date.getDate();
    let user_id = app.loginUser.id;
    this.getFirstDayOfWeek(cur_year, cur_month)
    this.calculateDays(cur_year, cur_month);
    this.calculateEmptyGrids(cur_year, cur_month)
    wx.showLoading({
      title: '加载中',
    })
    let startTime = this.data.dayList.days[0].day;
    let endTime = this.data.dayList.days[this.data.dayList.days.length - 1].day;
    let startDate = cur_year + '-' + cur_month + '-' + startTime + ' 00:00:00';
    let endDate = cur_year + '-' + cur_month + '-' + endTime + ' 23:59:59';
    this.setData({
      recordid: null
    })
    this.userData(user_id, startDate, endDate, cur_date);
    this.reality(user_id);
    this.ovulation(user_id);
    this.setData({
      cur_year, //年
      cur_month, //月
      cur_date //天
    })
  },
  renderPressStyle: function (year, month, day) { //渲染点击事件的样式
    var date = this.data.dayList;
    //渲染检测样式
    if (date.id === year + '-' + month) {
      var days = date.days;
      for (var i = 0; i < days.length; i++) {
        if (days[i].day == day) {
          days[i].class = "active"
        }
      }
    }
    this.setData({
      dayList: date
    })
  },
  onLoad(options) {
    wx.showTabBar({
      animation: true //是否需要过渡动画
    })
    wx.showShareMenu({
      withShareTicket: true
    })
    const user_id = app.loginUser.id;
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const cur_date = date.getDate();
    const now = date.getDate();
    const year_month = cur_year + '-' + cur_month;
    const weeks_ch = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    let cycle_day = cur_year + '-' + cur_month + '-' + cur_date;
    this.calculateEmptyGrids(cur_year, cur_month);
    this.calculateDays(cur_year, cur_month);
    this.getSystemInfo();
    wx.showLoading({
      title: '加载中',
    })
    var startTime = this.data.dayList.days[0].day;
    var endTime = this.data.dayList.days[this.data.dayList.days.length - 1].day;
    var startDate = cur_year + '-' + cur_month + '-' + startTime + ' 00:00:00';
    var endDate = cur_year + '-' + cur_month + '-' + endTime + ' 23:59:59';
    this.userData(user_id, startDate, endDate, cur_date)
    this.ovulation(user_id) //易排卵期
    this.reality(user_id) //实际例假期
    // showView: (options.showView == "true" ? true : false) //显示底部按钮是否高亮
    this.setData({
      cur_year, //年
      cur_month, //月
      cur_date, //天
      weeks_ch, //星期
      now,
      user_id, //用户id
      year_month,
      cycle_day,
      end_time: cur_year + "-12-31"
    })
  },
  reality: function (user_id) { //渲染真实例假期
    fetch('small/' + user_id + '/menstruation/info').then(res => {
      let cases = res.data.data.menstruationDate
      let all_cases = this.gainCases(cases);
      // 将所有例假开始时间拼成一个数组, 供计算
      var timeArr = all_cases.map(v => v[0]);
      this.setData({
        timeArr // 所有例假开始时间
      });
      let dayList = this.data.dayList;
      let cases_day = []
      let start_cases = [];
      for (var i = 0; i < all_cases.length; i++) {
        for (var j = 0; j < all_cases[i].length; j++) {
          let all_cases_date = all_cases[i][j].split("-")
          if (dayList.id == all_cases_date[0] + '-' + all_cases_date[1]) {
            cases_day.push(all_cases_date[2])
          }
        }
        start_cases.push(all_cases[i][0])
      }
      for (var i = 0; i < dayList.days.length; i++) {
        for (var j = 0; j < cases_day.length; j++) {
          if (dayList.days[i].day == cases_day[j]) {
            if (j == 0) {
              dayList.days[i].reality = 'cases1'
            } else if (j == cases_day.length - 1) {
              dayList.days[i].reality = 'cases2'
            } else {
              dayList.days[i].reality = 'cases'
            }
          }
        }
      }
      this.setData({
        dayList: dayList,
        cases_day,
        start_cases,
        begin_time: start_cases[0].split("-")[0] + "-01-01"
      })
    })
  },
  ovulation: function (user_id) { //预测例假跟易排卵期
    fetch('small/' + user_id + '/info').then(res => {
      let start_cases = res.data.data.startTime.split(" ")[0]
      let cycle_length = res.data.data.physiologicalLength - 14
      let physiologicalLength = res.data.data.physiologicalLength
      let menstruationLength = res.data.data.menstruationLength;
      this.setData({
        info: res.data.data
      })
      fetch('small/' + user_id + '/menstruation/info').then(res => {
        let startCases = res.data.data.menstruationDate.split(",")
        let all_start_cases = [];
        let dayList = this.data.dayList;
        for (var i = 0; i < startCases.length; i++) {
          var time1 = (startCases[i].split(":")) //所有的例假开始跟结束
          var time2 = time1[0].substr(0, 4) + '-' + time1[0].substr(4, 2) + '-' + time1[0].substr(6, 2);
          all_start_cases.push(time2)
        }
        this.setData({
          all_start_cases,
          startCases
        })
        let last_start_cases = this.formatDate(all_start_cases[all_start_cases.length - 1])
        let first_forecast_cases = this.formatDate(this.GetDateStr(last_start_cases, physiologicalLength))
        let last_forecast_cases = this.formatDate(this.GetDateStr(first_forecast_cases, (menstruationLength - 1)))
        let all_forecast_cases = this.add_date(first_forecast_cases, last_forecast_cases)
        let forecastCases = []
        for (var i = 0; i < all_forecast_cases.length; i++) {
          let all_forecast = all_forecast_cases[i].split("-")
          if (dayList.id == all_forecast[0] + "-" + all_forecast[1]) {
            forecastCases.push(all_forecast[2])
          }
        }
        for (var i = 0; i < dayList.days.length; i++) {
          for (var j = 0; j < forecastCases.length; j++) {
            if (dayList.days[i].day == forecastCases[j]) {
              if (j == 0) {
                dayList.days[i].forecast = 'forecastCases1'
              } else if (j == forecastCases.length - 1) {
                dayList.days[i].forecast = 'forecastCases2'
              } else {
                dayList.days[i].forecast = 'forecastCases'
              }
            }
          }
        }
        let vulations = []
        for (var i = 0; i < all_start_cases.length; i++) {
          var next_time = new Date(all_start_cases[i + 1])
          var start_time1 = new Date(all_start_cases[i])
          var s1 = next_time.getTime(),
            s2 = start_time1.getTime();
          var total = (s1 - s2) / 1000
          var day_num = parseInt(total / (24 * 60 * 60))
          var judge_length = physiologicalLength - 10;
          //判断，如果下次例假开始时间减去本次例假开始时间<生理周期长度-10，本次例假周期的易排卵不显示
          if (day_num < judge_length) {

          } else {
            var vulation1 = this.GetDateStr(all_start_cases[i], cycle_length);
            let all_vulation = this.tab(vulation1, 3);
            for (var j = 0; j < all_vulation.length; j++) {
              let all_vulation1 = all_vulation[j].split("-")
              if (dayList.id == all_vulation1[0] + '-' + all_vulation1[1]) {
                vulations.push(all_vulation1[2])
              }
            }
          }
        }
        for (var i = 0; i < dayList.days.length; i++) {
          for (var j = 0; j < vulations.length; j++) {
            if (dayList.days[i].day == vulations[j]) {
              if (j == 0) {
                dayList.days[i].Easy = 'ovulation1'
              } else if (j == vulations.length - 1) {
                dayList.days[i].Easy = 'ovulation2'
              } else {
                dayList.days[i].Easy = 'ovulation'
              }
            }
          }
        }
        this.setData({
          dayList,
          vulations,
          forecastCases
        })
      })
    })
  },
  GetDateStr: function (a, AddDayCount) { //几天后
    var dd = new Date(a);
    dd.setDate(dd.getDate() + AddDayCount);
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;
    var d = dd.getDate();
    return y + "-" + m + "-" + d;
  },
  tab: function (date, dNum) { //前后三天
    var arr = date.split('-');
    var fDay = [];
    for (var i = (parseInt(arr[2]) - dNum); i <= (parseInt(arr[2]) + dNum); i++) {
      var dd = new Date(arr[0], arr[1] - 1, i)
      var y = dd.getFullYear();
      var m = dd.getMonth() + 1; //获取当前月份的日期 
      var d = dd.getDate();
      fDay.push(y + "-" + m + "-" + d);
    }
    return fDay;
  },
  gainCases: function (casesData) { //所有的例假时间
    let cases = casesData.split(",")
    var all_cases = [];
    for (var i = 0; i < cases.length; i++) {
      var time1 = (cases[i].split(":")) //所有的例假开始跟结束
      var time2 = time1[0].substr(0, 4) + '-' + time1[0].substr(4, 2) + '-' + time1[0].substr(6, 2);
      var time3 = time1[1].substr(0, 4) + '-' + time1[1].substr(4, 2) + '-' + time1[1].substr(6, 2)
      var time4 = [];
      time4.push(time2);
      time4.push(time3)
      all_cases.push(this.add_date(time4[0], time4[1]))
    }
    return all_cases
  },
  add_date: function (start_time, end_time) { //根据开始跟结束补充中间的时间
    var bd = new Date(start_time),
      be = new Date(end_time);
    var bd_time = bd.getTime(),
      be_time = be.getTime(),
      time_diff = be_time - bd_time;
    var d_arr = [];
    for (var i = 0; i <= time_diff; i += 86400000) {
      var ds = new Date(bd_time + i);
      d_arr.push(ds.getFullYear() + '-' + (ds.getMonth() + 1) + '-' + ds.getDate())
    }
    return d_arr
  },
  userData: function (userId, startTime, endTime, cur_date) { //检测的数据
    fetch('small/' + userId + '/resistances?startTime=' + startTime + '&endTime=' + endTime).then(res => {
      wx.hideLoading()
      if (res.data.status == 200) {
        let data = res.data.data.dtos
        let detectionData = [];
        let detectionTimes = [];
        let dateItem = this.data.dayList
        for (var i = 0; i < data.length; i++) {
          if (data[i].sex) {
            for (var j = 0; j < dateItem.days.length; j++) {
              if ((i + 1) == dateItem.days[j].day) {
                dateItem.days[j].sex = '1'
                dateItem.days[j].recordId = data[i].recordId
                if (dateItem.days[j].day == cur_date) {
                  if (dateItem.days[j].recordId) {
                    this.setData({
                      recordid: dateItem.days[j].recordId
                    });
                    this.dailyRecords(dateItem.days[j].recordId)
                  }
                }
              }
            }
          }
          if (data[i].dtos) {
            detectionData.push(data[i].dtos)
          }
        }
        for (var i = 0; i < detectionData.length; i++) {
          for (var j = 0; j < detectionData[i].length; j++) {
            let detectionTime = detectionData[i][j].detectionTime
            detectionTimes.push(detectionTime.split(" "))
          }
        }
        for (let i = 0; i < detectionTimes.length; i++) {
          if (+detectionTimes[i][0].split("-")[1] < 10) {
            this.renderPressStyle(detectionTimes[i][0].split("-")[0], detectionTimes[i][0].split("-")[1].split("")[1], detectionTimes[i][0].split("-")[2])
          } else {
            this.renderPressStyle(detectionTimes[i][0].split("-")[0], detectionTimes[i][0].split("-")[1], detectionTimes[i][0].split("-")[2])
          }
        }
        this.details(cur_date, detectionData)
        this.setData({
          detectionData,
          detectionTimes,
        })
      }
    })
  },
  dailyRecords: function (e) { //查询本条记录
    let rid = e;
    let user_id = app.loginUser.id;
    fetch('small/' + user_id + '/dailyRecords/' + rid).then(res => {
      let dailyRecords_record = {}
      for (var key in res.data.data) {
        if (key !== 'cervicalMucusStatus') {
          dailyRecords_record[key] = res.data.data[key]
        }
      }
      wx.hideLoading()
      this.setData({
        dailyRecords_record
      })
    })
  },
  touchstart(e) {
    const t = e.touches[0];
    const startX = t.clientX;
    const startY = t.clientY;
    this.slideLock = true;
    this.setData({
      'gesture.startX': startX,
      'gesture.startY': startY
    });
  },
  touchmove(e) {
    let user_id = app.loginUser.id;
    if (isLeftSlide.call(this, e)) {
      this.setData({
        recordid: null
      })
      this.reality(user_id);
      this.ovulation(user_id);
      this.chooseNextMonth.call(this);
    }
    if (isRightSlide.call(this, e)) {
      this.setData({
        recordid: null
      })
      this.reality(user_id);
      this.ovulation(user_id);
      this.choosePrevMonth.call(this);
    }
  },
  choosePrevMonth() {
    wx.showLoading({
      title: '加载中',
    })
    const cur_year = this.data.cur_year;
    const cur_month = this.data.cur_month;
    let newMonth = cur_month - 1;
    let newYear = cur_year;
    let cur_date = this.data.cur_date;
    let detectionData = this.data.detectionData;
    let user_id = app.loginUser.id;
    if (newMonth < 1) {
      newYear = cur_year - 1;
      newMonth = 12;
    }
    this.calculateDays.call(this, newYear, newMonth);
    this.calculateEmptyGrids.call(this, newYear, newMonth);
    let startTime = this.data.dayList.days[0].day;
    let endTime = this.data.dayList.days[this.data.dayList.days.length - 1].day;
    let startDate = newYear + '-' + newMonth + '-' + startTime + ' 00:00:00';
    let endDate = newYear + '-' + newMonth + '-' + endTime + ' 23:59:59';
    this.userData(user_id, startDate, endDate, cur_date)
    this.details(cur_date, detectionData)
    this.setData({
      cur_year: newYear,
      cur_month: newMonth,
    })
  },
  chooseNextMonth() {
    wx.showLoading({
      title: '加载中',
    })
    const cur_year = this.data.cur_year;
    const cur_month = this.data.cur_month;
    let newMonth = +cur_month + 1;
    let newYear = cur_year;
    let cur_date = this.data.cur_date;
    let detectionData = this.data.detectionData;
    let user_id = app.loginUser.id;
    if (newMonth > 12) {
      newYear = +cur_year + 1;
      newMonth = 1;
    }
    this.calculateDays.call(this, newYear, newMonth);
    this.calculateEmptyGrids.call(this, newYear, newMonth);
    let startTime = this.data.dayList.days[0].day;
    let endTime = this.data.dayList.days[this.data.dayList.days.length - 1].day;
    let startDate = newYear + '-' + newMonth + '-' + startTime + ' 00:00:00';
    let endDate = newYear + '-' + newMonth + '-' + endTime + ' 23:59:59';
    this.userData(user_id, startDate, endDate, cur_date)
    this.details(cur_date, detectionData)
    this.setData({
      cur_year: newYear,
      cur_month: newMonth,
    })
  },
  handleCalendar(e) {
    wx.showLoading({
      title: '加载中',
    })
    let date = this.translateFormateDate(e.detail.value)
    let cur_date = this.data.cur_date;
    let detectionData = this.data.detectionData;
    let user_id = app.loginUser.id;
    this.setData({
      recordid: null
    })
    this.reality(user_id);
    this.ovulation(user_id);
    this.calculateDays.call(this, date[0], Number(date[1]));
    this.calculateEmptyGrids.call(this, date[0], Number(date[1]));
    let startTime = this.data.dayList.days[0].day;
    let endTime = this.data.dayList.days[this.data.dayList.days.length - 1].day;

    let startDate = date[0] + '-' + Number(date[1]) + '-' + startTime + ' 00:00:00';
    let endDate = date[0] + '-' + Number(date[1]) + '-' + endTime + ' 23:59:59';
    this.userData(user_id, startDate, endDate, cur_date)
    this.details(cur_date, detectionData)
    this.setData({
      cur_year: date[0],
      cur_month: Number(date[1]),
    })
  },
  translateFormateDate(date) {
    var year = date.split('-')[0]
    var month = date.split('-')[1]
    return [year, month]
  }
  // roommate() {
  //   // 同房日, showView true
  //   if ( this.data.showView !== true ) {
  //     this.setData({
  //       showView: (!this.data.showView)
  //     })
  //   }
  // },
  // detection() {
  //   // 检测日, showView false
  //   if ( this.data.showView !== false ) {
  //     this.setData({
  //       showView: (!this.data.showView)
  //     })
  //   }

  // }
};

Page(conf);